package controller;

import model.Product;
import model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import service.ProductService;
import service.UserService;
import util.Pagination;

@Controller
@RequestMapping(value = "user")
public class UserController extends BaseController{
    private UserService userService;
    private ProductService productService;

    public UserController(UserService userService, ProductService productService) {
        this.userService = userService;
        this.productService = productService;
    }

    //注册
    @PostMapping(value = "signUp")
    private String signUp(User user){
        if(userService.queryOne("queryUserByUsername",user.getUsername()) == null){
            userService.create(user);
            return "redirect:/index.jsp";
        }else {
            request.setAttribute("error","用户名已存在！");
            return "/signUp.jsp";
        }
    }

    //登录
    @PostMapping(value = "signIn")
    private String signIn(User user){
        user = userService.queryOne("queryUserByUsernameAndPassword",user);
        if (user == null){
            request.setAttribute("error","账号和密码错误！");
        }else {
            if (user.getRole() == 0){
                Pagination<Product> pagination = productService.queryAll(1);
                session.setAttribute("pagination", pagination);
            }
            session.setAttribute("user",user);
        }
        return "redirect:/index.jsp";
    }
    //退出登录
    @GetMapping(value = "signOut")
    private String signOut(){
        session.invalidate();
        return "redirect:/index.jsp";
    }
    //进入页面
    @GetMapping(value = "accessPage/{role}")
    private String accessPage(@PathVariable("role") int role){
        if (role == 1){
            return "redirect:/admin/index.html";
        }
        if (role == 0){
            return "redirect:/user/index.html";
        }
        return "";
    }

    @GetMapping(value = "queryAll/{currentPage}")
    private String queryAllProducts(@PathVariable("currentPage") int currentPage){
        Pagination<Product> pagination = productService.queryAll(currentPage);
        session.setAttribute("pagination", pagination);
        return "redirect:/index.jsp";
    }
}
